package com.shuorikeji.huohuo.ui.dj

import android.app.Dialog
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.WindowManager
import android.widget.ImageView
import com.bytedance.sdk.djx.DJXRewardAdResult
import com.bytedance.sdk.djx.DJXSdk
import com.bytedance.sdk.djx.IDJXWidget
import com.bytedance.sdk.djx.interfaces.listener.IDJXDramaListener
import com.bytedance.sdk.djx.interfaces.listener.IDJXDramaUnlockListener
import com.bytedance.sdk.djx.model.DJXDrama
import com.bytedance.sdk.djx.model.DJXDramaDetailConfig
import com.bytedance.sdk.djx.model.DJXDramaUnlockAdMode
import com.bytedance.sdk.djx.model.DJXDramaUnlockInfo
import com.bytedance.sdk.djx.model.DJXDramaUnlockMethod
import com.bytedance.sdk.djx.model.DJXUnlockModeType
import com.bytedance.sdk.djx.params.DJXWidgetDramaDetailParams
import com.bytedance.sdk.openadsdk.AdSlot
import com.bytedance.sdk.openadsdk.TTAdConstant
import com.bytedance.sdk.openadsdk.TTAdLoadType
import com.bytedance.sdk.openadsdk.TTAdNative
import com.bytedance.sdk.openadsdk.TTAdSdk
import com.bytedance.sdk.openadsdk.TTRewardVideoAd
import com.shuorikeji.huohuo.R
import com.shuorikeji.huohuo.base.BasePresenterActivity
import com.shuorikeji.huohuo.bean.DjDetailMainBean
import com.shuorikeji.huohuo.callback.ClickCallBack
import com.shuorikeji.huohuo.common.Constant
import com.shuorikeji.huohuo.mvp.AllPresenter
import com.shuorikeji.huohuo.utils.BusinessUtils
import com.shuorikeji.huohuo.utils.CustomStatusBarUtil
import com.shuorikeji.huohuo.utils.DialogUtil
import com.shuorikeji.huohuo.utils.PreUtils
import com.shuorikeji.huohuo.utils.ToastShowUtil

class DjXqActivity : BasePresenterActivity<AllPresenter>() {
    companion object {
        private const val TAG = "DjXqActivity"
    }

    private lateinit var ivDz: ImageView
    private lateinit var ivZj: ImageView

    // 计时器相关变量
    private lateinit var handler: Handler
    private lateinit var timerRunnable: Runnable
    private var isRunning = false
    private var totalWatchedSeconds: Long = 0L

    // 解锁剧集数量
    private var unlockSet = Constant.CSJ_DRAMA_UNLOCK_SET

    // 免费集数
    private var freeEpisodes = Constant.CSJ_FREE_SET
    private var playSet = 1

    // 1-后台获取vid,2-穿山甲
    private var type = "2"
    private var dramaId: Long = 0
    private var vlId: Long = 0
    private lateinit var dialog: Dialog
    private lateinit var widget: IDJXWidget
    private var dramaBean = ""
    private var rewardVerify = false

    // 当前播放集数
    private var currentIndex = -1
    private var isFirst = true
    private lateinit var djXqBean: DjDetailMainBean

    private val dramaUnlockListener: IDJXDramaUnlockListener = object : IDJXDramaUnlockListener {
        override fun unlockFlowStart(
            drama: DJXDrama,
            callback: IDJXDramaUnlockListener.UnlockCallback,
            map: Map<String, Any>?
        ) {
            Log.i("wxl", "穿山甲短剧未解锁unlockFlowStart: ")
            dialog = DialogUtil.showJsAdDialog(this@DjXqActivity, object : ClickCallBack {
                override fun onClick(flag: Int, `object`: Any?) {
                    if (flag == 1) {
                        callback.onConfirm(
                            DJXDramaUnlockInfo(
                                dramaId,
                                unlockSet,
                                DJXDramaUnlockMethod.METHOD_AD,
                                false,
                                null,
                                true,
                                DJXUnlockModeType.UNLOCKTYPE_DEFAULT
                            )
                        )
                    } else if (flag == 2) {
                        val curDjTime = System.currentTimeMillis()
                        val lastDjTime = PreUtils.get(Constant.CSJ_AD_SEE_TIME, 0L) as Long
                        if (lastDjTime == 0L) {
                            PreUtils.put(Constant.CSJ_AD_SEE_TIME, curDjTime)
                            callback.onConfirm(
                                DJXDramaUnlockInfo(
                                    dramaId,
                                    unlockSet,
                                    DJXDramaUnlockMethod.METHOD_AD,
                                    false,
                                    null,
                                    false,
                                    DJXUnlockModeType.UNLOCKTYPE_DEFAULT
                                )
                            )
                        } else {
                            if (BusinessUtils.longTimeSjc(curDjTime, lastDjTime) > 600) {
                                PreUtils.put(Constant.CSJ_AD_SEE_TIME, curDjTime)
                                callback.onConfirm(
                                    DJXDramaUnlockInfo(
                                        dramaId,
                                        unlockSet,
                                        DJXDramaUnlockMethod.METHOD_AD,
                                        false,
                                        null,
                                        false,
                                        DJXUnlockModeType.UNLOCKTYPE_DEFAULT
                                    )
                                )
                            } else {
                                ToastShowUtil.showToastCenter(
                                    this@DjXqActivity,
                                    "距上次观看广告不超过10分钟，请稍后再观看广告"
                                )
                            }
                        }
                    }
                }
            })
        }

        override fun showCustomAd(
            drama: DJXDrama,
            callback: IDJXDramaUnlockListener.CustomAdCallback
        ) {
            Log.i("wxl", "showCustomAd: ")
            val adNative = TTAdSdk.getAdManager().createAdNative(this@DjXqActivity)
            val adSlot = AdSlot.Builder()
                .setCodeId(Constant.REWARD_DRAMA)
                .setOrientation(TTAdConstant.ORIENTATION_VERTICAL)
                .setAdLoadType(TTAdLoadType.LOAD)
                .build()
            adNative.loadRewardVideoAd(adSlot, object : TTAdNative.RewardVideoAdListener {
                override fun onError(code: Int, msg: String) {
                    ToastShowUtil.showToastCenter(
                        this@DjXqActivity,
                        "短剧广告onError: $code,msg: $msg"
                    )
                }

                override fun onRewardVideoAdLoad(ad: TTRewardVideoAd) {
                    ad.setRewardAdInteractionListener(object :
                        TTRewardVideoAd.RewardAdInteractionListener {
                        override fun onAdShow() {
                            Log.i(TAG, "onAdShow: ")
                            callback.onShow(ad.mediationManager.showEcpm.ecpm)
                            dialog.dismiss()
                        }

                        override fun onAdVideoBarClick() {
                            Log.i(TAG, "onAdVideoBarClick: ")
                        }

                        override fun onAdClose() {
                            Log.i(TAG, "onAdClose: ")
                            if (!rewardVerify) {
                                callback.onRewardVerify(DJXRewardAdResult(false))
                                rewardVerify = false
                            }
                        }

                        override fun onVideoComplete() {
                            Log.i(TAG, "onVideoComplete: ")
                        }

                        override fun onVideoError() {
                            Log.e(TAG, "onVideoError: ")
                            callback.onError()
                        }

                        @Deprecated("Deprecated in Java")
                        override fun onRewardVerify(
                            b: Boolean,
                            i: Int,
                            s: String,
                            i1: Int,
                            s1: String
                        ) {
                        }

                        override fun onRewardArrived(b: Boolean, i: Int, bundle: Bundle) {
                            Log.i(TAG, "onRewardArrived: $b")
                            callback.onRewardVerify(DJXRewardAdResult(b))
                            rewardVerify = b
                            try {
                                allSeeAdDy(
                                    "穿山甲",
                                    ad.mediationManager.showEcpm.ecpm
                                )
                            } catch (e: Exception) {
                                e.printStackTrace()
                            }
                            mPresenter.djAdJsDj(
                                true, 1, myId, currentIndex, 2
                            ) { flag, `object` ->
                                when (flag) {
                                    1 -> {
                                        //getDjDetail()
                                        // 创建剧集播放
                                        widget = DJXSdk.factory()
                                            .createDramaDetail(
                                                DJXWidgetDramaDetailParams.obtain(
                                                    dramaId,
                                                    playSet,
                                                    obtainConfig()
                                                )
                                            )
                                        runOnUiThread {
                                            if (!isFinishing && !isDestroyed && !supportFragmentManager.isStateSaved) {
                                                getSupportFragmentManager().beginTransaction()
                                                    .replace(R.id.frame_layout, widget.fragment)
                                                    .commit();
                                            }
                                        }
                                    }

                                    2 -> {
                                        val msg = `object` as String
                                        ToastShowUtil.showToastCenter(this@DjXqActivity, msg)
                                    }
                                }
                            }
                        }

                        override fun onSkippedVideo() {
                            Log.i(TAG, "onSkippedVideo: ")
                        }
                    })
                    ad.showRewardVideoAd(this@DjXqActivity)
                }

                @Deprecated("Deprecated in Java")
                override fun onRewardVideoCached() {
                }

                override fun onRewardVideoCached(ttRewardVideoAd: TTRewardVideoAd) {
                }
            })
        }

        override fun unlockFlowEnd(
            drama: DJXDrama,
            errCode: IDJXDramaUnlockListener.UnlockErrorStatus?,
            map: Map<String, Any>?
        ) {
            Log.i(TAG, "unlockFlowEnd: $errCode")
            Log.i(TAG, "unlockFlowEnd: $map")
        }
    }

    private val dramaListener: IDJXDramaListener = object : IDJXDramaListener() {

        // 开始播放
        override fun onDJXVideoPlay(p0: MutableMap<String, Any>?) {
            super.onDJXVideoPlay(p0)
            Log.d(TAG, "开始播放")
            if (p0 != null) {
                currentIndex = p0["index"].toString().toInt()
            }
            if (!isRunning) {
                startTimer()
            }
        }

        // 暂停播放
        override fun onDJXVideoPause(p0: MutableMap<String, Any>?) {
            super.onDJXVideoPause(p0)
            Log.d(TAG, "暂停播放")
            if (isRunning) {
                pauseTimer()
            }
        }

        // 继续播放
        override fun onDJXVideoContinue(p0: MutableMap<String, Any>?) {
            super.onDJXVideoContinue(p0)
            Log.d(TAG, "继续播放")
            if (!isRunning) {
                startTimer()
            }
        }

        // 播放完成
        override fun onDJXVideoCompletion(p0: MutableMap<String, Any>?) {
            super.onDJXVideoCompletion(p0)
            Log.d(TAG, "播放完成")
            if (isRunning) {
                pauseTimer()
            }
        }

        // 播放结束
        override fun onDJXVideoOver(p0: MutableMap<String, Any>?) {
            super.onDJXVideoOver(p0)
            Log.d(TAG, "播放结束")
            if (isRunning) {
                pauseTimer()
            }
        }

        override fun onDJXClose() {
            super.onDJXClose()
            Log.d(TAG, "界面关闭")
        }

        override fun onDJXRequestStart(p0: MutableMap<String, Any>?) {
            super.onDJXRequestStart(p0)
            Log.d(TAG, "请求开始")

        }

        override fun onDJXRequestFail(p0: Int, p1: String?, p2: MutableMap<String, Any>?) {
            super.onDJXRequestFail(p0, p1, p2)
            Log.d(TAG, "请求失败")
        }

        override fun onDJXRequestSuccess(p0: MutableList<MutableMap<String, Any>>?) {
            super.onDJXRequestSuccess(p0)
            Log.d(TAG, "请求成功")
            // 首次加载，播放上次进度
            if (currentIndex != -1 && isFirst) {
                widget.currentDramaIndex = currentIndex
                isFirst = false
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        getmImmersionBar().reset().statusBarColor(R.color.transparent).statusBarDarkFont(true, 0.2f)
            .init();
        CustomStatusBarUtil.with(this).init();

    }

    fun initView() {
        dramaId = intent.getLongExtra("dramaId", 0)
        playSet = intent.getIntExtra("playSet", 1)
        dramaBean = intent.getStringExtra("dramaBean") ?: ""
        type = intent.getStringExtra("type") ?: "2"
        if (type == "1") {
            vlId = dramaId
        }
//        widget = DJXSdk.factory()
//            .createDramaDetail(DJXWidgetDramaDetailParams.obtain(dramaId, playSet, obtainConfig()))
//        getSupportFragmentManager().beginTransaction()
//            .replace(R.id.frame_layout, widget.fragment)
//            .commit();
//        FragmentUtils.add(supportFragmentManager, widget.fragment, R.id.frame_layout)

        // 保持常亮
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)

        // 初始化Handler
        handler = Handler(Looper.getMainLooper())

        // 初始化计时器Runnable
        timerRunnable = object : Runnable {
            override fun run() {
                if (isRunning) {
                    totalWatchedSeconds++
//                    updateTimerUI()
                    // 30秒记录一次，要不后台触发不了金币
                    if (totalWatchedSeconds >= 30) {
                        totalWatchedSeconds = 0
//                        if (UserUtils.isLogin)
//                            presenter.postForm(COIN_LOG_ADD_REDIS, CodeMsgBean::class.java, mapOf("sec" to 30))
                    }
                    Log.d(TAG, "播放时长${totalWatchedSeconds}")
                    handler.postDelayed(this, 1000) // 每秒执行一次
                }
            }
        }
    }

    private fun obtainConfig(): DJXDramaDetailConfig {
        val adMode = DJXDramaUnlockAdMode.MODE_SPECIFIC
        return DJXDramaDetailConfig.obtain(adMode, freeEpisodes, dramaUnlockListener)
            .hideRewardDialog(true)
            .hideMore(true)
            .hideDoubleClick(true)
            .hideLikeButton(true)
            .hideFavorButton(true)
            .listener(dramaListener)
    }

    fun initListener() {
        ivDz.setOnClickListener {
            mPresenter.djDz(
                true, myId, widget.currentDramaIndex
            ) { flag, `object` ->
                when (flag) {
                    1 -> {
                        if (djXqBean.data?.love_status == 1) {
                            djXqBean.data?.love_status = 2
                        } else {
                            djXqBean.data?.love_status = 1
                        }
                        updateStatus()
                    }

                    2 -> {
                        val msg = `object` as String
                        ToastShowUtil.showToastCenter(this@DjXqActivity, msg)
                    }
                }
            }
        }
        ivZj.setOnClickListener {
            mPresenter.addDeleteZj(
                true, myId, widget.currentDramaIndex, 1
            ) { flag, `object` ->
                when (flag) {
                    1 -> {
                        if (djXqBean.data?.follow_status == 1) {
                            djXqBean.data?.follow_status = 2
                        } else {
                            djXqBean.data?.follow_status = 1
                        }
                        updateStatus()
                    }

                    2 -> {
                        val msg = `object` as String
                        ToastShowUtil.showToastCenter(this@DjXqActivity, msg)
                    }
                }
            }
        }
//        vb.imgShare.setOnClickListener {
//            if (UserUtils.isLogin) {
//                startActivity(Intent(this, InviteActivity::class.java))
//            } else LoginPwdActivity.start()
//        }
    }


    override fun initData() {
        initView()
        getDjDetail()
    }

    private fun allSeeAdDy(sdkName: String, ecpm: String) {
        mPresenter.allSeeAdDy(
            false, "coin_look_video", ecpm, 2, sdkName
        ) { flag, `object` ->
            when (flag) {
                1 -> {}
                2 -> {
                    val msg = `object` as String
                    ToastShowUtil.showToastCenter(this@DjXqActivity, msg)
                }
            }
        }
    }

    private fun getDjDetail() {
        mPresenter.djDetail(
            true, dramaId, type.toInt(), dramaBean
        ) { flag, `object` ->
            when (flag) {
                1 -> {
                    djXqBean = `object` as DjDetailMainBean
                    if (djXqBean.code == 1) {
                        myId = djXqBean.data?.id ?: 0
                        freeEpisodes = djXqBean.data?.free_episodes ?: 1
                        updateStatus()
                    }
                    if (type == "1") {
                        dramaId = djXqBean.data?.csj?.shortplay_id?.toLong() ?: 0
                    }
                    if (djXqBean.data.look_data != null) {
                        playSet = djXqBean.data.look_data.vid
                    } else {
                        playSet = 1
                    }
                    // 创建剧集播放
                    widget = DJXSdk.factory()
                        .createDramaDetail(
                            DJXWidgetDramaDetailParams.obtain(
                                dramaId,
                                playSet,
                                obtainConfig()
                            )
                        )
                    runOnUiThread {
                        if (!isFinishing && !isDestroyed && !supportFragmentManager.isStateSaved) {
                            getSupportFragmentManager().beginTransaction()
                                .replace(R.id.frame_layout, widget.fragment)
                                .commit();
                        }
                    }
                }

                2 -> {
                    val msg = `object` as String
                    ToastShowUtil.showToastCenter(this, msg)
                }
            }
        }
    }

    override fun onPause() {
        super.onPause()
//        if (UserUtils.isLogin) {
//            // 记录观看的集数
//            presenter.postForm(
//                VIDEO_LOOK_ADD,
//                CodeMsgBean::class.java,
//                mapOf("vl_id" to myId, "vid" to widget.currentDramaIndex, "min" to 0)
//            )
//            // 记录时长
//            presenter.postForm(
//                COIN_LOG_ADD_REDIS,
//                CodeMsgBean::class.java,
//                mapOf("sec" to totalWatchedSeconds)
//            )
//        }
    }

    override fun onDestroy() {
        super.onDestroy()
        try {
            if (widget != null) {
                widget.destroy()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
    }

    override fun setContentView() {
        setContentView(R.layout.activity_csj_dj_xq);
        ivDz = findViewById(R.id.img_like)
        ivZj = findViewById(R.id.img_collect)
        initListener()
    }

    private var myId = 0

    private fun updateStatus() {
        if (djXqBean.data?.love_status == 1) {
            ivDz.setImageResource(R.mipmap.icon_dj_detail_ydz)
        } else {
            ivDz.setImageResource(R.mipmap.icon_dj_detail_dz)
        }
        if (djXqBean.data?.follow_status == 1) {
            ivZj.setImageResource(R.mipmap.icon_dj_detail_ysc)
        } else {
            ivZj.setImageResource(R.mipmap.icon_dj_detail_sc)
        }
    }

    private fun startTimer() {
        if (!isRunning) {
            isRunning = true
            handler.post(timerRunnable)
//            btn_play_pause.text = "暂停"
        }
    }

    private fun pauseTimer() {
        isRunning = false
        handler.removeCallbacks(timerRunnable)
//        btn_play_pause.text = "播放"
    }

    private fun resetTimer() {
        isRunning = false
        handler.removeCallbacks(timerRunnable)
        totalWatchedSeconds = 0L
//        updateTimerUI()
//        btn_play_pause.text = "播放"
    }

//    private fun updateTimerUI() {
//        val hours = totalWatchedSeconds / 3600
//        val minutes = (totalWatchedSeconds % 3600) / 60
//        val seconds = totalWatchedSeconds % 60
//
//        tv_timer.text = String.format("%02d:%02d:%02d", hours, minutes, seconds)
//    }
}